/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年6月3日
 */
package com.massyframework.beanskin.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 服务加载工具类
 * @author huangkh
 *
 */
public abstract class ServiceLoaderUtils {

	/**
	 * 使用spi加载{@code servieType}类型的单个服务。
	 * @param <T>
	 * @param serviceType {@link Class},服务类型
	 * @return {@link T}
	 */
	public static <T> T loadService(Class<T> serviceType) {
		ServiceLoader<T> sl = ServiceLoader.load(serviceType);
		Iterator<T> it = sl.iterator();
		return it.hasNext() ? it.next() : null;
	}
	
	/**
	 * 使用spi加载{@code servieType}类型的单个服务。
	 * @param <T>
	 * @param serviceType {@link Class},服务类型
	 * @param classLoader {@link ClassLoader,类加载器
	 * @return {@link T}
	 */
	public static <T> T loadService(Class<T> serviceType, ClassLoader classLoader) {
		ServiceLoader<T> sl = ServiceLoader.load(serviceType, classLoader);
		Iterator<T> it = sl.iterator();
		return it.hasNext() ? it.next() : null;
	}
	
	/**
	 * 使用spi加载{@code servieType}类型的服务集合。
	 * @param <T>
	 * @param serviceType {@link Class}, 服务类型
	 * @return {@link List}
	 */
	public static <T> List<T> loadServies(Class<T> serviceType){
		ServiceLoader<T> sl = ServiceLoader.load(serviceType);
		Iterator<T> it = sl.iterator();
		
		List<T> result = new ArrayList<>();
		while (it.hasNext()) {
			result.add(it.next());
		}
		return result;
	}
	
	/**
	 * 使用spi加载{@code servieType}类型的服务集合。
	 * @param <T>
	 * @param serviceType {@link Class}, 服务类型
	 * @param classLoader {@link ClassLoader,类加载器
	 * @return {@link List}
	 */
	public static <T> List<T> loadServies(Class<T> serviceType, ClassLoader classLoader){
		ServiceLoader<T> sl = ServiceLoader.load(serviceType, classLoader);
		Iterator<T> it = sl.iterator();
		
		List<T> result = new ArrayList<>();
		while (it.hasNext()) {
			result.add(it.next());
		}
		return result;
	}

}
